package com.idanchuang.component.logback.converter;


import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.idanchuang.component.logback.appender.DcILoggingEvent;
import com.idanchuang.component.logback.web.filter.RequestStartTimeFilter;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UrlPatternConverter extends ClassicConverter {

    private static boolean IS_WEB = true;

    @Override
    public String convert(ILoggingEvent le) {
        if (le instanceof DcILoggingEvent) {
            return ((DcILoggingEvent) le).getUrl();
        }
        return figure(le);
    }

    public static String figure(ILoggingEvent iLoggingEvent) {
        String url = RequestStartTimeFilter.REQUEST_URL_THREAD_LOCAL.get();
        if (url != null) {
            return url;
        }
        if (!IS_WEB) {
            return "-";
        }
        try {
            Class.forName("org.springframework.web.context.request.RequestContextHolder");
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                return req.getRequestURL().toString();
            }
        } catch (ClassNotFoundException e) {
            IS_WEB = false;
        } catch (Exception e) {
            // ignore
        }
        return "-";
    }

}
